<?php
class Func_Authorization
{

	/**
	 * Starts a user session if the login details are correct.
	 * Password must be in md5 format.
	 * 
	 * @param $username
	 * @param md5 $password
	 */
	public static function login($username, $password){
        
    	Validate::notNull(TBL_PASSWORD_FIELDNAME, "Please define the 'TBL_PASSWORD_FIELDNAME' named constant in Func.php");
    	Validate::notNull(TBL_USER_TBLNAME, "Please define the 'TBL_USER_TBLNAME' named constant in Func.php");
    	Validate::notNull(TBL_USERNAME_FIELDNAME, "Please define the 'TBL_USERNAME_FIELDNAME' named constant in Func.php");
    	
    	$db = new Func_Db();
    	
    	$dbPassword = $db->queryForString("select " . TBL_PASSWORD_FIELDNAME . " from " . TBL_USER_TBLNAME .
    		" where " . TBL_USERNAME_FIELDNAME . " = '$username'");

    	// user doesn't exist
    	if($dbPassword == null){
    		return false;
    	}
    	
    	// login user
    	if($password === $dbPassword){
    		//TODO: if required, add browser agent to session id
    		$sid = md5($username);
    		Func_Session::setId($sid);
    		Func_Session::start();
    		Func_Session::addToSession("username", $username);
    		return true;
    	}
    	
    	Func_Session::destroy();
    	return false;
    }
    
    /**
     * check whether the user is logged in.
     * 
     * @param $username
     */
    public static function userLoggedIn(){
  	
    	// continue session, or start new one
		Func_Session::start();
		
		if(Func_Session::getSessionValue("username") != null){
			if(md5(Func_Session::getSessionValue("username")) == Func_Session::getId()){
				return true;
			}
		}
		
		// existing session did not exist, destroy this one
		Func_Session::destroy();
		return false;
	}

	
    public static function logout(){
        Func_Session::destroy();
    }
}
?>